<script setup>
import router from "../../../router/index.js";
import MyNav from "../../../components/MyNav.vue";
import MyForm from "../../../components/MyForm.vue";
import {RULE} from "../../../const/index.js";
import {onMounted, reactive, ref} from "vue";
import {insertApi, simpleListApi} from "../../../util/axios.js";
import {getResponseData} from "../../../util/request.js";
import {isNotNull} from "../../../util/index.js";

/* ==================== 页面常量 ==================== */

// 路径导航
const navItems = [
  {icon: 'Notebook', label: '课程管理'},
  {icon: 'Notebook', label: '课程列表', url: '/Course'},
  {icon: 'Plus', label: '添加课程'},
];

/* ==================== 全查课程类别 ==================== */

let categoryOptions = ref([]);

/** 全查课程类别 */
async function listCategory() {
  categoryOptions.value = [];
  let res = await simpleListApi(null, {module: 'category'});
  let data = getResponseData(res);
  if (isNotNull(data)) {
    data.forEach((item) => {
      let category = {};
      category['label'] = item['title'];
      category['value'] = item['id'];
      categoryOptions.value.push(category);
    });
  }
}

/* ==================== 添加表单 ==================== */

// 表单项 + 表单值 + 表单规则
let items = ref([
  {label: '标题', prop: 'title', required: true},
  {label: '排序', prop: 'idx', type: 'number', min: 1, required: true, span: 12},
  {label: '作者', prop: 'author', required: true, span: 12},
  {
    label: '类别', prop: 'fkCategoryId', required: true, span: 12,
    type: 'select', options: categoryOptions, placeholder: '请选择课程类别'
  },
  {label: '价格', prop: 'price', type: 'number', min: 1, required: true, span: 12},
  {label: '描述', prop: 'info', required: true, type: 'textarea'},
]);
let data = reactive({info: '暂无描述'});
let rules = {
  title: RULE.TITLE,
  author: RULE.AUTHOR,
  info: RULE.INFO,
};

/**
 * 添加成功后调用
 *
 * 1. 路由到 Course 页面
 */
function insertSuccess() {
  router.push('/Course');
}

/* ==================== 加载函数 ==================== */

onMounted(() => listCategory());

</script>

<template v-if="categoryOptions">
  <my-nav :items="navItems"/>
  <el-divider/>
  <el-card class="course-insert-card" header="添加课程">
    <my-form type="insert"
             :items="items"
             :rules="rules"
             :args="{module: 'course'}"
             :api="insertApi"
             :params="data"
             :callback="insertSuccess"/>
  </el-card>
</template>

<style scoped lang="scss">
.course-insert-card {
  width: 70%; // 宽度
  margin: 20px auto 0; // 外边距
}
</style>